//
//  ViewController.m
//  WebpTest
//
//  Created by KakaCompany on 13/1/15.
//  Copyright (c) 2015 KakaCompany. All rights reserved.
//

#import "ViewController.h"
#import "WAImgCompressUtil.h"
#import "UIImage+WebP.h"

@interface ViewController ()
{
  NSString *filePath;
}

//mainRepo change Test

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)addPhoto:(id)sender
{
  UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"本地",nil];
  [sheet showInView:self.view];
  [sheet release];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
  if (buttonIndex == 0)
  {
    [self takePhoto];
  }
  else if(buttonIndex == 1)
  {
    [self chooseFromLocal];
  }
}

- (void)takePhoto
{
  UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
  if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
  {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    //设置拍照后的图片可被编辑
    picker.allowsEditing = YES;
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:nil];
    [picker release];    
  }else
  {
    NSLog(@"模拟其中无法打开照相机,请在真机中使用");
  }
}

- (void)chooseFromLocal
{
  UIImagePickerController *picker = [[UIImagePickerController alloc] init];
  
  picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  picker.delegate = self;
  //设置选择后的图片可被编辑
  picker.allowsEditing = YES;
  [self presentViewController:picker animated:YES completion:nil];
  [picker release];
}

-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
  NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
  
  //当选择的类型是图片
  if ([type isEqualToString:@"public.image"])
  {
    //先把图片转成NSData
    UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    [self writeToPhotoAlbum:image];
    //关闭相册界面
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    NSDate *datenow = [NSDate date];
    NSString *nowtimeStr = [formatter stringFromDate:datenow];
    [self normalThenWebpCompress:image withFileName:nowtimeStr];
    [self newWebpCompress:image withFileName:nowtimeStr];
    
  }
  
}

- (void)writeToPhotoAlbum:(UIImage *)aImage
{
  UIImageWriteToSavedPhotosAlbum(aImage, nil, nil, nil);
}
//先执行压缩，再进行webp压缩
- (void)normalThenWebpCompress:(UIImage *)aImage withFileName:(NSString *)aFilename
{
  NSDate *timenow = [NSDate date];
  NSString *photoType = nil;
  NSData *data;
  if (UIImagePNGRepresentation(aImage) == nil)
  {
    data = UIImageJPEGRepresentation(aImage, 1.0);
    photoType = @"jpg";
  }
  else
  {
    data = UIImagePNGRepresentation(aImage);
    photoType = @"png";
  }
  NSString *originalPath = [[self filePath:aFilename]stringByAppendingPathComponent:[NSString stringWithFormat:@"originalimage.%@",photoType]];
  [data writeToFile:originalPath atomically:YES];
  NSData *firstData = [CWAImgCompressUtil compressImageWAStyle:aImage];
  UIImage *firstImage = [UIImage imageWithData:firstData];
  //压缩后写入
  NSString *firstPath = [[self filePath:aFilename]stringByAppendingPathComponent:[NSString stringWithFormat:@"compressimage.%@",photoType]];
  [firstData writeToFile:firstPath atomically:YES];
  [UIImage imageToWebP:firstImage quality:1.0f alpha:1.0f preset:WEBP_PRESET_PHOTO
                            completionBlock:^(NSData *result) {
                              UIImage *secondImage = [UIImage imageWithWebPData:result];
                              [iNormView setImage:secondImage];
                              NSString *webPPath = [[self filePath:aFilename]stringByAppendingPathComponent:@"image.webp"];
                              
                              if ([result writeToFile:webPPath atomically:YES]) {
                                uint64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:webPPath error:nil] fileSize];
                                [iNormalLabel setText:[NSString stringWithFormat:@"File size: %.2f KB, Time:%@ ", (double)fileSize/1024,[self compareCurrentTime:timenow]]];
                              }
                            } failureBlock:^(NSError *error) {
                              
                            }];

}

//原图进行webp压缩
- (void)newWebpCompress:(UIImage *)aImage withFileName:(NSString *)aFilename
{
  NSDate *timenow = [NSDate date];
  [UIImage imageToWebP:aImage quality:1.0f alpha:1.0f preset:WEBP_PRESET_PHOTO
       completionBlock:^(NSData *result) {
         UIImage *secondImage = [UIImage imageWithWebPData:result];
         [iConvertView setImage:secondImage];
         NSString *webPPath = [[self filePath:aFilename]stringByAppendingPathComponent:@"newimage.webp"];
         
         if ([result writeToFile:webPPath atomically:YES]) {
           uint64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:webPPath error:nil] fileSize];
           [iConvertLabel setText:[NSString stringWithFormat:@"File size: %.2f KB, Time:%@", (double)fileSize/1024,[self compareCurrentTime:timenow]]];
         }
       } failureBlock:^(NSError *error) {
         
       }];
}

- (NSString *)filePath:(NSString *)timestr
{
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *webPPath = [paths[0] stringByAppendingString:timestr];
  return webPPath;
}

- (NSString *) compareCurrentTime:(NSDate*) compareDate
{
  NSTimeInterval  timeInterval = [compareDate timeIntervalSinceNow];
  timeInterval = -timeInterval;
  div_t h = div(timeInterval, 3600);
//  int hours = h.quot;
  // Divide the remainder by 60; the quotient is minutes, the remainder
  // is seconds.
  div_t m = div(h.rem, 60);
  int minutes = m.quot > 0? m.quot:0;
  int seconds = m.rem > 0? m.rem:0;
  div_t s = div(m.rem, 60);
  int mseconds = s.quot >0? s.quot:0;
  NSString *result = [NSString stringWithFormat:@"%dm%ds%dms",minutes,seconds,mseconds];
  return  result;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
  NSLog(@"您取消了选择图片");
  [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)dealloc
{
  [iNormView release];
  [iConvertView release];
  [iNormalLabel release];
  [iConvertLabel release];
  [super dealloc];
}
@end
